package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.EquipPatrolCheckWorkOrder;
import cc.comac.mom.bean.EquipPatrolCheckWorkOrderBean;
import cc.comac.mom.bean.EquipPatrolCheckWorkOrderItem;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipPatrolCheckPlanItemDao;
import cc.comac.mom.dao.entity.EquipPatrolCheckWorkOrderDao;
import cc.comac.mom.dao.entity.EquipPatrolCheckWorkOrderItemDao;
import cc.comac.mom.entity.EquipPatrolCheckPlanItemEntity;
import cc.comac.mom.entity.EquipPatrolCheckWorkOrderEntity;
import cc.comac.mom.entity.EquipPatrolCheckWorkOrderItemEntity;
import cc.comac.mom.redis.IdFactory;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Component
@Transactional
public class EquipPatrolCheckWorkOrderDataHandler extends ServiceImpl<EquipPatrolCheckWorkOrderDao, EquipPatrolCheckWorkOrderEntity>{
	@Autowired 
	private EquipPatrolCheckWorkOrderDao equipPatrolCheckWorkOrderDao;
	
	@Autowired 
	private EquipPatrolCheckWorkOrderItemDao equipPatrolCheckWorkOrderItemDao;
	
	@Autowired 
	private EquipPatrolCheckWorkOrderItemDataHandler equipPatrolCheckWorkOrderItemDataHandler;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	@Autowired
	private EquipPatrolCheckPlanItemDao EquipPatrolCheckPlanItemDao;
	
	@Autowired
	private IdFactory idFactory;
	//批量生成巡检检验工单
	public ResultBean insertBatch(List<EquipPatrolCheckWorkOrder> list) {
		ResultBean resultBean = new ResultBean(true);
		if(list == null || list.size()<1) {
			throw new RuntimeException("数据为空");
		}
		ArrayList<EquipPatrolCheckWorkOrderEntity> listEntity = new ArrayList<EquipPatrolCheckWorkOrderEntity>();
		ArrayList<EquipPatrolCheckWorkOrderItem> listWorkOrderItem = new ArrayList<EquipPatrolCheckWorkOrderItem>();
		for(EquipPatrolCheckWorkOrder item :list) {
			EquipPatrolCheckWorkOrderEntity innerData = item.getInnerData();
			if(innerData ==null) {
				throw new RuntimeException("数据为空");	
			}
			if (StringUtils.isNotEmpty(innerData.getCreator())) {
				innerData.setId(idFactory.generateId());
				//	entity.setSiteId(idUtil.getSiteId());
				innerData.setCreationTime(TimeUtil.getLocalDateTime());
				innerData.setCreationTimeZone(TimeUtil.getLocalTimeZone());
				innerData.setLastModifiedTime(TimeUtil.getLocalDateTime());
				innerData.setLastModifiedTimeZone(TimeUtil.getLocalTimeZone());
				innerData.setRowStatus(1);
			} else {
				baseEntityDataUtil.setBaseEntityData(innerData);
			}
//			baseEntityDataUtil.setBaseEntityData(innerData);
			listEntity.add(innerData);
	    	QueryWrapper<EquipPatrolCheckPlanItemEntity> queryWrapper = new QueryWrapper<EquipPatrolCheckPlanItemEntity>();
	    	queryWrapper.eq("row_status",1);
	    	queryWrapper.eq("patrol_check_id",innerData.getPatrolCheckId());
	    	List<EquipPatrolCheckPlanItemEntity> selectList = EquipPatrolCheckPlanItemDao.selectList(queryWrapper);
	    	if(selectList!=null && selectList.size()>0) {
	    		for(EquipPatrolCheckPlanItemEntity item2:selectList) {
		    		EquipPatrolCheckWorkOrderItem equipPatrolCheckWorkOrderItem = new EquipPatrolCheckWorkOrderItem();
		    		EquipPatrolCheckWorkOrderItemEntity equipPatrolCheckWorkOrderItemEntity = new EquipPatrolCheckWorkOrderItemEntity();
		    		equipPatrolCheckWorkOrderItemEntity.setDevId(item2.getDevId());
		    		equipPatrolCheckWorkOrderItemEntity.setPatrolCheckOrderId(innerData.getId());
		    		equipPatrolCheckWorkOrderItemEntity.setCreator(innerData.getCreator());
		    		equipPatrolCheckWorkOrderItemEntity.setLastModifier(innerData.getLastModifier());
		    		equipPatrolCheckWorkOrderItem.setInnerData(equipPatrolCheckWorkOrderItemEntity);
		    		listWorkOrderItem.add(equipPatrolCheckWorkOrderItem);
	    		}
	    	}else{
				throw new RuntimeException("巡检明细不能为空");
			}
		}
		boolean saveBatch = this.saveBatch(listEntity);
		if(!saveBatch) {
			throw new RuntimeException("保存巡检工单失败");
		}
		ResultBean resultBean2 = equipPatrolCheckWorkOrderItemDataHandler.insertBatch(listWorkOrderItem);
		if(!resultBean2.success) {
			throw new RuntimeException(resultBean2.getMessage());
		}
		return resultBean;
	}
	//查询
	public ResultDev selectByFields(EquipPatrolCheckWorkOrderBean obj) {
		ResultDev resultDev = new ResultDev();
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		obj.setPageNum((obj.getPageNum()-1)*obj.getPageSize());
		List<EquipPatrolCheckWorkOrderBean> listEquipRegularCheckPlanBean = equipPatrolCheckWorkOrderDao.selectByFields(obj);
		long countByFields = equipPatrolCheckWorkOrderDao.selectCountByFields(obj);
		
		// 将查询总数除以每页数量后向上取整获取总页数
		double pageCount = Math.ceil((double)countByFields / obj.getPageSize());
		resultDev.setEntityList(listEquipRegularCheckPlanBean);
		resultDev.setPageCount((int)pageCount);
		resultDev.setTotalQuantity((int)countByFields);
		return resultDev;
	}
	
// 修改执行用时
	public ResultBean updateExecuteTime(EquipPatrolCheckWorkOrder obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipPatrolCheckWorkOrderEntity innerData = obj.getInnerData();
		EquipPatrolCheckWorkOrderEntity selectById = equipPatrolCheckWorkOrderDao.selectById(innerData.getId());
		if (selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		if (selectById.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTED) {
			throw new RuntimeException("执行未完成，不能修改");
		}
		selectById.setActualExecuteTime(innerData.getActualExecuteTime());
		baseEntityDataUtil.updateBaseEntityData(selectById);
		int updateById = equipPatrolCheckWorkOrderDao.updateById(selectById);
		if (updateById < 1) {
			throw new RuntimeException("调整执行用时失败");
		}
		return resultBean;
	}
	
	//批量删除巡检计划工单
	public ResultBean deleteBatch(List<Long> ids) {
		ResultBean resultBean = new ResultBean(true);
		if (ids == null || ids.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		List<EquipPatrolCheckWorkOrderEntity> selectBatchIds = equipPatrolCheckWorkOrderDao.selectBatchIds(ids);
		if (selectBatchIds == null || selectBatchIds.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		for (EquipPatrolCheckWorkOrderEntity item : selectBatchIds) {
			if (item.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
				throw new RuntimeException("工单号:" + item.getWorkNumber() + " 已执行，不可删除");
			}
			baseEntityDataUtil.deleteBaseEntityData(item);
		}
		boolean updateBatchById = this.updateBatchById(selectBatchIds);
		if (!updateBatchById) {
			throw new RuntimeException("批量删除巡检计划工单失败");
		}
		// 删除子项
		ArrayList<EquipPatrolCheckWorkOrderItemEntity> listItem = new ArrayList<EquipPatrolCheckWorkOrderItemEntity>();
		for (EquipPatrolCheckWorkOrderEntity item : selectBatchIds) {
			QueryWrapper<EquipPatrolCheckWorkOrderItemEntity> queryWrapper = new QueryWrapper<EquipPatrolCheckWorkOrderItemEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("patrol_check_order_id", item.getId());
			List<EquipPatrolCheckWorkOrderItemEntity> list = equipPatrolCheckWorkOrderItemDao
					.selectList(queryWrapper);
			if (list != null && list.size() > 0) {
				listItem.addAll(list);
			}
		}
		if (listItem != null && listItem.size() > 0) {
			for (EquipPatrolCheckWorkOrderItemEntity item : listItem) {
				baseEntityDataUtil.deleteBaseEntityData(item);
			}
			boolean updateBatchById2 = equipPatrolCheckWorkOrderItemDataHandler.updateBatchById(listItem);
			if (!updateBatchById2) {
				throw new RuntimeException("批量删除巡检计划工单项失败");
			}
		}
		return resultBean;
	}

	// 开始执行
	public ResultBean planStartExecute(EquipPatrolCheckWorkOrder obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipPatrolCheckWorkOrderEntity innerData = obj.getInnerData();
		EquipPatrolCheckWorkOrderEntity selectById = equipPatrolCheckWorkOrderDao.selectById(innerData.getId());
		if (selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		if (selectById.getStatus() != MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
			throw new RuntimeException("该计划工单已经开始执行，不能再次开始");
		}
		selectById.setFirstExecuteStartDate(new Date());
		selectById.setActualExecuteTime(new BigDecimal(0));
		selectById.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTEING);
		baseEntityDataUtil.updateBaseEntityData(selectById);
		int updateById = equipPatrolCheckWorkOrderDao.updateById(selectById);
		if (updateById < 1) {
			throw new RuntimeException("开始执行失败");
		}
		return resultBean;
	}
}
